package tools.nexus;

import java.util.ArrayList;


import tools.fasta.FastaSeq;

public class NexusSet {

	private ArrayList<FastaSeq> seqs;
	
	private String gap="-";
	private boolean isDna;
	private int nameLength,nchar;
	
	public NexusSet(ArrayList<FastaSeq> in,boolean isDna){
		this.isDna=isDna;
		nameLength=0;
		nchar=in.get(0).getSeq().length();
		seqs= new ArrayList<FastaSeq>();
		boolean differentLengths=false;
		String name;
		int length;
		for (FastaSeq seq : in) {
			name=seq.getHeader().split(" ")[0].substring(1);
			if(name.length()>nameLength){
				nameLength=name.length();
			}
			length=seq.getSeq().length();
			if(length!=nchar){
				differentLengths=true;
				if(length>nchar){
					nchar=length;
				}
			}
			seqs.add(new FastaSeq(name,seq.getSeq()));
		}
		if(differentLengths){
			System.err.println("Transcripts have different lengths... will fill up with -");
			String tmp;
			for (FastaSeq seq : seqs) {
				if(seq.getSeq().length()!=nchar){
					tmp=seq.getSeq();
					while(tmp.length()<nchar){
						tmp+=gap;
					}
					seq.setSeq(tmp);
				}
			}
		}
	}
	
	public void print2Screen(){
		System.out.println(header());
		int j=0,linelength=80,i;
		int seqLength=linelength-nameLength-1;
		for(;j<nchar/seqLength;j++){
			for (FastaSeq seq : seqs) {
				System.out.print(seq.getHeader());
				for(i=seq.getHeader().length();i<nameLength+1;i++){
					System.out.print(" ");
				}
				System.out.println(seq.getSeq().substring(j*(seqLength), (j+1)*seqLength));
			}
			System.out.println();
		}
		for (FastaSeq seq: seqs) {
			System.out.print(seq.getHeader());
			for(i=seq.getHeader().length();i<nameLength+1;i++){
				System.out.print(" ");
			}
			System.out.println(" "+seq.getSeq().substring(j*seqLength, nchar));
		}
		System.out.println(tail());
	}
	

	
	
	private boolean isDna(char c){
		c=(""+c).toUpperCase().charAt(0);
		switch (c) {
		case 'A':
			return true;
		case 'T':
			return true;
		case 'G':
			return true;
		case 'C':
			return true;
		case 'N':
			return true;
		case '-':
			return true;
		default:
			return false;
		}
	}
	
	private String header(){
		String h="#NEXUS\n\n";
		h+="BEGIN DATA;\n";
		h+="dimensions ntax="+seqs.size()+" nchar="+nchar+";\n";
		h+="format missing=?\n";
		h+="interleave datatype="+(isDna?"DNA":"PROTEIN")+" gap= "+gap+";\n\n";
		h+="matrix";
		
		return h;
	}
	
	private String tail(){
		return ";\nend;";
	}
}
